//
//  MusicDownloadTask.m
//  DownLoadDemo
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "MusicDownloadTask.h"

@interface MusicDownloadTask ()<NSURLSessionDownloadDelegate>

@property (nonatomic,strong) ProgressBlock progressBlock;
@property (nonatomic,strong) ComplateBlock complateBlock;
@property (nonatomic,strong) NSString *mp3Name;

@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

@end


@implementation MusicDownloadTask

- (void)downloadUrl:(NSURL *)url progresBlock:(ProgressBlock)proBlock complate:(ComplateBlock)comBlock {
    self.progressBlock = proBlock;
    self.complateBlock = comBlock;
    self.mp3Name = [url.absoluteString stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    self.mp3Name = [self.mp3Name stringByReplacingOccurrencesOfString:@":" withString:@"_"];
    
    // 网络请求
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.downloadTask = [session downloadTaskWithURL:url];
    // 启动任务
    [self.downloadTask resume];
    
}
#pragma mark - NSURLSessionDownloadDelegate
/// 下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    // 下载进度
    float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
    NSLog(@"%.2f",progress);
    // 回调block
    if (self.progressBlock) {
        self.progressBlock(progress);
    }
    
}
/// 下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"%@",[location path]);
    
    /// 得到Caches文件目录
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.mp3Name]];
    /// 移动到caches文件夹
    [[NSFileManager defaultManager]moveItemAtPath:[location path] toPath:filePath error:nil];
    NSLog(@"%@",filePath);
    
    
    if (self.complateBlock) {
        self.complateBlock(filePath);
    }
}


/// 开始
- (void)resume {
    [self.downloadTask resume];
}
/// 暂停
- (void)suspend {
    [self.downloadTask suspend];
}


/// 修改Block
- (void)setProgressBlock:(ProgressBlock)proBlock {
    if (_progressBlock != proBlock) {
        _progressBlock = proBlock;
    }
}
- (void)setComplateBlock:(ComplateBlock)comBlock {
    if (_complateBlock != comBlock) {
        _complateBlock = comBlock;
    }
}



@end
